import { APP_CODE } from "../config/index";
// 获取存储
export const getStorage = (key) => {
  if (APP_CODE) {
    return getStorageByAppCode(key);
  } else {
    return getStorageByNormal(key);
  }
};
// 设置存储
export const setStorage = (key, value) => {
  if (APP_CODE) {
    setStorageByAppCode(key, value);
  } else {
    setStorageByNormal(key, value);
  }
};
// 删除存储
export const removeStorage = (key) => {
  if (APP_CODE) {
    removeStorageByAppCode(key);
  } else {
    removeStorageByNormal(key);
  }
};
// 获取所有存储并针对APP_CODE进行删除
export const removeAllStorage = () => {
  if (APP_CODE) {
    removeAllStorageByAppCode();
  } else {
    removeAllStorageByNormal();
  }
};
// 获取APP_CODE的存储
const getStorageByAppCode = (key) => {
  let dataJson = localStorage.getItem(key);
  let data = null;
  if (dataJson) {
    data = JSON.parse(dataJson)[APP_CODE];
  }
  if (data) {
    return JSON.parse(data);
  }
  return null;
};

//获取普通存储
const getStorageByNormal = (key) => {
  let dataJson = localStorage.getItem(key);
  let data = null;
  if (dataJson) {
    data = JSON.parse(dataJson);
  }
  return data;
};

//设置APP_CODE存储
const setStorageByAppCode = (key, value) => {
  // 判断是否有key
  let dataJson = localStorage.getItem(key);
  let data = null;
  if (dataJson) {
    data = JSON.parse(dataJson);
    data[APP_CODE] = "";
  } else {
    // 创建一个空对象
    data = {
      [APP_CODE]: "",
    };
  }
  data[APP_CODE] = value;
  // 储存data
  localStorage.setItem(key, JSON.stringify(data));
};

//设置普通存储
const setStorageByNormal = (key, value) => {
  localStorage.setItem(key, JSON.stringify(value));
};

//删除APP_CODE存储
const removeStorageByAppCode = (key) => {
  // 判断是否有key
  let dataJson = localStorage.getItem(key);
  let data = null;
  if (dataJson) {
    data = JSON.parse(dataJson);
    delete data[APP_CODE];
  }
  // 储存data
  localStorage.setItem(key, JSON.stringify(data));
};

//删除普通存储
const removeStorageByNormal = (key) => {
  localStorage.removeItem(key);
};

// 获取所有存储并针对APP_CODE进行删除
const removeAllStorageByAppCode = () => {
  let dataJson = localStorage;
  for (let key in dataJson) {
    let jsonData = JSON.parse(dataJson[key]);
    if (jsonData[APP_CODE]) {
      delete jsonData[APP_CODE];
      // 储存data
      localStorage.setItem(key, JSON.stringify(jsonData));
    }
  }
};

// 普通全部删除
const removeAllStorageByNormal = () => {
  localStorage.clear();
};
